package com.tarcemap.gpsmobileappgui;



import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MapView.LayoutParams;
import com.google.android.maps.Overlay;
import com.tracemap.gpslocation.R;

public class WannaShowRouteActivity extends MapActivity {

	MapView mapView;
	MapController mapC;
	GeoPoint p;
	String locationName;
	
	double lat = 40.006428;
	double lng = 116.476970;
	private static final int ZOOMSCALE = 17;
	private static final int ZOOM_IN=Menu.FIRST;   
	private static final int ZOOM_OUT=Menu.FIRST+1; 
	private static final int CHANGE_VIEW=Menu.FIRST+2;
	private static final int BACKTOHOME=Menu.FIRST+3;
	private static final int SHOWMAKER=Menu.FIRST+4;
	private static final int SEARCHSOMEONE=Menu.FIRST+5;
	boolean SEARCHSOMEONEToggle=false;
	boolean SHOWMAKERToggle=false;
	OverLayRoute routeOverlay;
	
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wannashowroute);

		routeOverlay = new OverLayRoute(getResources());
		
		p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
		mapView = (MapView) findViewById(R.id.maps);

		mapView.displayZoomControls(false);
		//取得MapController实例，控制地图  
		MapController mapController=mapView.getController();  
	     //设置显示模式  
	     //myMapView.setSatellite(true);  
		mapView.setStreetView(true);  
	     //设置缩放控制,这里我们自己实现缩放菜单  
		mapView.displayZoomControls(false);     
	     //设置使用MyLocationOverlay来绘图  
	     mapController.setZoom(17);  

		// adding overlay
		// MapsOverlay mapOverlay = new MapsOverlay();
		// List<Overlay> listOfOverlays = mapView.getOverlays();
		// listOfOverlays.clear();
		// listOfOverlays.add(mapOverlay);
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	// Menu Creation
	public boolean onCreateOptionsMenu(Menu menu) {
		//menu.add(0, 1, 0, "Zoom");
		menu.add(0, ZOOM_IN, Menu.NONE, "放大");  
	    menu.add(0, ZOOM_OUT, Menu.NONE, "缩小"); 
		menu.add(0, CHANGE_VIEW, 0, "ChangeView");
		menu.add(0, BACKTOHOME, 0, "Show WangJing");
		menu.add(0, SHOWMAKER, 0, "Show Marker");
		menu.add(0, SEARCHSOMEONE, 0, "Search Location");
		return true;
	}

	// When meniItem Clikced
	public boolean onOptionsItemSelected(MenuItem item) {
		final MapController mapController = mapView.getController();
		super.onOptionsItemSelected(item);  
	    
	    
		switch (item.getItemId()) {
		case (ZOOM_IN):  
            //放大  
            mapController.zoomIn();  
            break;  
        case (ZOOM_OUT):  
            //缩小  
            mapController.zoomOut();  
            break; 
		
		case CHANGE_VIEW:
			AlertDialog dialog = new AlertDialog.Builder(WannaShowRouteActivity.this).setItems(
					R.array.selectMapView,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							if (which == 0) {
								mapView.setSatellite(true);
							} else if (which == 1) {
								mapView.setStreetView(true);
							} else if (which == 2) {
								mapView.setSatellite(false);
								mapView.setStreetView(false);
							}
						}

					}).create();
			dialog.setTitle("Select MapView");
			dialog.show();
			break;
		case BACKTOHOME:

			GeoPoint geoP = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
			mapController.animateTo(geoP);
			mapController.setCenter(geoP);
			mapController.setZoom(ZOOMSCALE);
//			mapView.invalidate();
			break;
		case SHOWMAKER:
			List<Overlay> listOfOverlays = mapView.getOverlays();
			listOfOverlays.clear();
			if (SHOWMAKERToggle){
				mapView.invalidate();
				SHOWMAKERToggle = false;
				break;
			}
			SHOWMAKERToggle = true;
			MapsOverlay mapOverlay = new MapsOverlay();
			
			listOfOverlays.add(mapOverlay);
			List<GeoPoint> locations=new ArrayList<GeoPoint>();
			locations.add(new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)));
			locations.add(new GeoPoint((int) (40.006128 * 1E6), (int) (116.476170 * 1E6)));
			locations.add(new GeoPoint((int) (40.006328 * 1E6), (int) (116.476270 * 1E6)));
			routeOverlay.setLocation(locations);
			listOfOverlays.add(routeOverlay);
			mapView.invalidate();
			break;
		case SEARCHSOMEONE:
			LinearLayout searchLayout = (LinearLayout) findViewById(R.id.searchlayout);
			if (SEARCHSOMEONEToggle==true){
				searchLayout.setVisibility(LinearLayout.INVISIBLE);
				SEARCHSOMEONEToggle = false;
				break;
			}
			
			SEARCHSOMEONEToggle = true;			
			searchLayout.setVisibility(LinearLayout.VISIBLE);
			final EditText location = (EditText) findViewById(R.id.location);
			Button searchButton = (Button) findViewById(R.id.search);
			searchButton.setOnClickListener(new OnClickListener() {

				public void onClick(View view) {
					locationName = location.getText().toString();
					// Reverse Geocoding
					Geocoder geoCoder = new Geocoder(WannaShowRouteActivity.this, Locale.getDefault());
					try {
						Log.i("1111111111", "111111111111");
						List<Address> addresses = geoCoder.getFromLocationName(
								locationName, 5);
						Log.i("222222222222", "2222222222");
						// String add = "";
						if (addresses.size() > 0) {

							p = new GeoPoint((int) (addresses.get(0)
									.getLatitude() * 1E6), (int) (addresses
									.get(0).getLongitude() * 1E6));
							Log.i("333333333", "33333333333");
							mapController.animateTo(p);
							mapController.setZoom(6);
							mapView.invalidate();
						} else {
							Toast.makeText(WannaShowRouteActivity.this,
									"Sorry, you typed wrongly, Try again",
									Toast.LENGTH_LONG).show();
						}
						//SHOWMAKERToggle = false;
						//onOptionsItemSelected(SHOWMAKER);
					} catch (Exception e) {
						Log.i("Error, while getting location",
								"Error, while getting location");
						e.printStackTrace();
					}
				}

			});

			break;
		}
		return true;
	}

	// when key 0 pressed, zoomIn(), and for 1, zoomOut()
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		MapController mc = mapView.getController();
		switch (keyCode) {

		case KeyEvent.KEYCODE_0:
			mc.zoomIn();
			break;
		case KeyEvent.KEYCODE_1:
			mc.zoomOut();
			break;
		}
		return super.onKeyDown(keyCode, event);
	}
	class MapsOverlay extends com.google.android.maps.Overlay {

		public boolean draw(Canvas canvas, MapView mapview, boolean shadow,
				long when) {
			super.draw(canvas, mapview, shadow);
			Point screenPts = new Point();
			// converting geoPoint to screen co-ordinates
			mapview.getProjection().toPixels(p, screenPts);

			Bitmap bmp = BitmapFactory.decodeResource(getResources(),
					R.drawable.bubble);
			canvas.drawBitmap(bmp, screenPts.x-12, screenPts.y-34, null);
			return true;
		}

		// showing Lat & Longi on every user click
		public boolean onTouchEvent(MotionEvent event, MapView mapview) {
			Log.i("in onTouchEvent() : ", "in onTouchEvent() : ");
			if (event.getAction() == MotionEvent.ACTION_UP) {
				// converting screen co-ordinates to geoPoint
				GeoPoint p = mapview.getProjection().fromPixels(
						(int) event.getX(), (int) event.getY());
				Toast.makeText(
						getBaseContext(),
						"Latitude : " + p.getLatitudeE6() / 1E6 + ","
								+ "Longitude : " + p.getLongitudeE6() / 1E6,
						Toast.LENGTH_SHORT).show();

				// Geocoding
				Geocoder geoCoder = new Geocoder(getBaseContext(), Locale
						.getDefault());
				try {
					List<Address> addresses = geoCoder
							.getFromLocation(p.getLatitudeE6() / 1E6, p
									.getLongitudeE6() / 1E6, 1);

					String add = "";
					if (addresses.size() > 0) {
						for (int i = 0; i < addresses.get(0)
								.getMaxAddressLineIndex(); i++)
							add += addresses.get(0).getAddressLine(i) + "\n";
					}
					Toast.makeText(getBaseContext(), add, Toast.LENGTH_LONG)
							.show();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return true;
			} else {
				return false;
			}
		}
	}
}
